<!DOCTYPE html>
<html>
<!-- 本代码仅以提供学习与研究，不可用于任何商业用途，如果违反，造成的一切后果由使用者全部承担 -->

<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="./static/css/index.min.css">
  <link rel="stylesheet" type="text/css" href="http://cdn.bootcss.com/font-awesome/4.6.0/css/font-awesome.min.css">
  <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
  <title id="title">极简音乐</title>
</head>

<body>
  <!-- 背景图 -->
  <img src="./static/image/back12.jpg" class="back">
  <div id="app">
    <div class="loveImgAndCounts" :class="{fadeout:isFadeOut}" @click="emerge()">
      <div class="img"><img src="./static/image/LoveHeart.png" class="loveHeart"></div>
      <div class="span" :class="{hide:isEmerge}"><span>{{loves.length}}</span></div>
    </div>
    <div class="drag">
      <span> 极简音乐，简单听音乐 </span>
    </div>
    <!-- 搜索栏 -->
    <div class="part1" :class="{fadeout:isFadeOut}">
      <input @keydown.enter="explore()" ref="input1" type="text" placeholder="搜索音乐" id="input" @focus="focus($event)"
        @blur="blur($event)">
    </div>
    <!-- 搜索结果和我的喜欢 -->
    <div class="part2">
      <template v-if="songs.length!=0">
        <div class="playLists" :class="{fadeout:isFadeOut}">

          <div class="playListTitle">
            <span>搜索结果</span>
          </div>
          <div class="playListMenu">
            <span>歌名</span>
            <span>歌手</span>
          </div>
          <template v-for="(song,index) in songs">
            <div class="playList" @click="submit(song.name,song.author,index,song.url,$event,song.flag)">
              <div><span>{{song.name}} </span>
                <template v-if="song.flag==1">
                  <img src="./static//image/kuwo.png">
                </template>
                <template v-else-if="song.flag==2">
                  <img class="wangyiyun" src="./static//image/wangyiyun.png">
                </template>
              </div>
              <span>{{song.author}}</span>
            </div>
          </template>
        </div>
      </template>
      <div class="runningLists" :class="{fadeout:isFadeOut,border:songs.length!=0,loading:isEmerge}">
        <div class="runningListMenu">
          <span>我喜欢的</span>
        </div>
        <template v-for="(love,index) in loves">
          <div class="runningList" @click="submit(love.name,love.author,index,love.url,$event,love.flag)"
            :id="createID(index)">
            <div>
              <span>{{love.name}}</span>
              <template v-if="love.flag==1">
                <img src="./static//image/kuwo.png">
              </template>
              <template v-else-if="love.flag==2">
                <img class="wangyiyun" src="./static//image/wangyiyun.png">
              </template>
            </div>
            <span>{{love.author}}</span>
          </div>
        </template>
      </div>
    </div>
    <!-- 进度条 -->
    <div class="part3" :class="{fadeout:isFadeOut}">
      <progress id="process" max="100" value="0"></progress>
    </div>
    <!-- 播放,下一首，上一首等显示部件 -->
    <div class="part4" :class="{fadeout:isFadeOut}">
      <div class="song">
        <div class="songName">{{songName}}</div>
        <div class="songAuthor">{{songAuthor}}</div>
      </div>
      <div class="span"><span>{{currentTime}} / {{timeLength}}</span></div>

      <div class="changeLast" @click="last()"></div>
      <div class="img " @click="rotate()"><img id="img" src="./static/image/play.png"></div>
      <div class="changeNext" @click="next()"></div>

      <div class="volume">
        <img ref="myvolume" src="./static/image/volume.png">
        <div class="volumeNumber">
          <span> {{volume}}%</span>
        </div>
      </div>
    </div>
    <!-- 加载动画 -->
    <div class="transition-loader" :class="{loading:isLoading}">
      <div class="transition-loader-inner">
        <label></label>
        <label></label>
        <label></label>
        <label></label>
        <label></label>
        <label></label>
      </div>
    </div>
    <!-- 放大缩小关闭按钮，采用绝对定位 -->
    <div class="iconSelector" :class="{fadeout:isFadeOut}">
      <div class="shadow"><img src="./static/image/smaller.png" @click="smaller()"></div>
      <div class="shadow"><img src="./static/image/bigger.png" @click="bigger()"></div>
      <div class="shadow"><img src="./static/image/close.png" @click="close()"></div>
    </div>
  </div>
</body>
<script>
  // 引入通信，爬虫，解析等库
  const { ipcRenderer } = require('electron')
  const request = require('request')
  const cheerio = require('cheerio')
  Vue.prototype.$request = request
  Vue.prototype.$cheerio = cheerio
  Vue.prototype.$ipcRenderer = ipcRenderer
  var app = new Vue({
    el: '#app',
    data() {
      return {
        flag: 0,
        isFadeOut: false,
        isEmerge: true,
        isMouseDown: false,
        isLoading: true,
        event: null,
        timeLength: "00:00",
        currentTime: '00:00',
        volume: 0,
        songName: "",
        songAuthor: "",
        songs: [],
        loves: [],
      }
    },
    mounted() {
      // 对非渲染全局变量在加载完成时定义
      this.title = document.querySelector('#title')
      this.id = 0
      this.clientWidth = 0
      this.rotateVal = 0
      this.audio = new Audio()
      this.audio.volume = 0.35
      this.volume = Math.floor(this.audio.volume * 100)
      this.origin()
      this.move()
      this.keyDown()
      this.volumeChange = this.$refs.myvolume
      this.process = document.querySelector('#process')
      this.$ipcRenderer.on("originData", (event, arg) => {
        if (!event) {
          this.$ipcRenderer.send('again')
        }
        this.loves = arg
      })
      this.$ipcRenderer.send('start')
      // 监听窗口关闭事件，将喜欢歌曲全部写入csv表格，方便下次启动时加载
      this.$ipcRenderer.on('willingClose', () => {
        this.$ipcRenderer.send('loves', this.loves)
      })
      // 进度条点击
      this.process.onclick = (event) => {
        if (!this.audio.duration) {
          return
        }
        this.progressChange(event)
      }
      // 播放完切歌
      this.audio.onended = () => {
        clearInterval(this.InterVal)
        this.id++
        this.changeSong()
      }
      // 滑轮调节音量
      this.volumeChange.onmouseover = () => {
        document.onmousewheel = (e) => {
          this.volumeChangeFunc(e)
        }
      }
      this.volumeChange.onmouseout = () => {
        document.onmousewheel = null
      }
      // 进度条拖拉
      this.process.onmousedown = () => {
        if (!this.audio.duration) {
          return
        }
        this.isMouseDown = !this.isMouseDown
        document.onmousemove = (event) => {
          this.progressChange(event)
        }
      }
      document.onmouseup = () => {
        if (!this.audio.duration) {
          return
        }
        document.onmousemove = null
        if (this.isMouseDown) {
          this.isMouseDown = !this.isMouseDown
        }
      }
    },
    methods: {
      // 下一首
      next() {
        this.id++
        // 0代表手动切换
        this.changeSong()
      },
      // 上一首
      last() {
        this.id--
        this.changeSong()
      },
      // 播放完毕或点击下一首和上一首切换歌曲，输入变量e判断为手动切换还是自动切换
      changeSong() {
        if (this.loves.length == 0) {
          return
        }
        else {
          if (this.id >= this.loves.length) {
            this.id = 0
          }
          else if (this.id < 0) {
            this.id = this.loves.length - 1
          }
          var a = document.querySelector('#List' + this.id)
          a.click()
        }
      },
      // 创建我的喜欢列表中每个歌曲的唯一识别码，为后面的模拟点击事件提供基础
      createID(e) {
        return "List" + e
      },
      // 最小化
      smaller() {
        // 与主进程通信
        this.$ipcRenderer.send('smaller')
      },
      // 最大化
      bigger() {
        this.$ipcRenderer.send('bigger')
      },
      // 关闭
      close() {
        this.$ipcRenderer.send('close')
      },
      // 搜索爬取歌曲网页，并解析歌曲id和歌曲名字及歌手名字
      explore() {
        this.isLoading = false
        var temp = this.isEmerge
        this.isEmerge = true
        this.songs = []
        var exploreValue = encodeURI(this.$refs.input1.value)
        var options = [{
          url: 'https://music.hwkxk.cf/?kw=' + exploreValue + '&source=kuwo',
          headers: {
            'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'
          }
        },
        {
          url: 'https://music.hwkxk.cf/?kw=' + exploreValue + '&source=wy',
          headers: {
            'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'
          }
        },
        ];
        for (let i = 0; i < 2; i++) {
          this.$request(options[i], (err, response, data) => {
            let result = []
            let id = []
            if (response.statusCode == 404) {
              let option = {
                title: "数据请求失败",
                body: "请检查网络连接，也有可能服务器跑丢了"
              }
              new Notification(option.title, option)
              return
            }
            let $ = this.$cheerio.load(data)
            $('td[class=song-name]').each((index, element) => {
              if (index == 0) { }
              else {
                let temp = $(element).text().split('-')
                result.push({
                  name: temp[1],
                  author: temp[0],
                  flag: i + 1,
                  url: ""
                })
              }
            })
            $('td[class=song-bitrate] a').each((index, element) => {
              if ($(element).hasClass('btn-info')) {
                id.push($(element).attr('href').match(/\d+/g))
              }
            })
            for (var j = 0; j < result.length; j++) {
              result[j].url = id[j][0]
              this.songs.push(result[j])
            }
            this.isLoading = true
            this.isEmerge = temp
          })
        }
      },
      // 调节音量，并消息栏警告音量是否超过最大健康限度
      volumeChangeFunc(e) {
        var e = e || window.event
        if (e.wheelDelta) {  //判断浏览器IE，谷歌滑轮事件
          if (e.wheelDelta > 0 && this.volume < 99) { //当滑轮向上滚动时
            this.audio.volume += 0.01
            this.volume = Math.floor(this.audio.volume * 100)
            if (this.volume == 80) {
              let option = {
                title: '警告！音量超过80%！',
                body: '请注意保护听力健康',
              }
              new Notification(option.title, option)
            }
          }
          if (e.wheelDelta < 0 && this.volume > 0) { //当滑轮向下滚动时
            this.audio.volume -= 0.01
            this.volume = Math.floor(this.audio.volume * 100)
          }
        }
      },
      // 改变进度条，并同时改变播放时间，以及播放音乐的进度
      progressChange(e) {
        var e = event || window.event
        var progressLength = e.clientX - this.process.offsetLeft
        if (progressLength < 0) {
          this.process.value = 0
          this.audio.currentTime = 0
        }
        else if (progressLength > this.process.offsetWidth) {
          this.process.value = this.process.max
          this.audio.currentTime = this.audio.duration
        }
        else {
          this.process.value = (progressLength / this.process.offsetWidth) * this.process.max
          this.audio.currentTime = (progressLength / this.process.offsetWidth) * this.audio.duration
        }
      },
      // 关闭或打开我的喜欢
      emerge() {
        this.isEmerge = !this.isEmerge
      },
      // 设置15s无操作息屏事件
      origin() {
        this.timer = setTimeout(() => {
          this.flag = 1
          this.isFadeOut = true
        }, 15000);
      },
      // 搜索框输入时禁止息屏事件
      keyDown() {
        this.$refs.input1.onkeydown = () => {
          if (this.flag == 1) {
            this.flag = 0
            this.isFadeOut = false
          }
          clearTimeout(this.timer)
          this.origin()
        }
      },
      // 鼠标移动禁止息屏事件
      move() {
        document.body.addEventListener('mousemove', () => {
          if (this.flag == 1) {
            this.flag = 0
            this.isFadeOut = false
          }
          clearTimeout(this.timer)
          this.origin()
        })
      },
      // 使播放图标进行旋转
      rotateImg() {
        this.InterVal = setInterval(() => {
          var img = document.getElementById('img')
          this.rotateVal += 1
          img.style.transform = 'rotate(' + this.rotateVal + 'deg)'
          img.style.transition = 'all 0.1s linear'
        }, 100)
      },
      // 点击播放图标使其旋转
      rotate() {
        if (!this.audio.duration) {
          return
        }
        if (this.audio.paused) {
          this.audio.play()
          this.rotateImg()
        }
        else {
          this.audio.pause()
          clearInterval(this.InterVal)
        }
      },
      // 点击页面的歌曲进行判断是否播放，切歌，暂停，添加喜欢，剔除相同喜欢歌曲，图标旋转等一系列复杂逻辑
      submit(e1, e2, e3, e4, e5, e6) {
        if (e3 != this.event || this.clientWidth != e5.srcElement.clientWidth) {
          this.songName = "缓冲中..."
          this.title.innerHTML = "极简音乐"
          this.songAuthor = ""
          this.timeLength = "00:00"
          clearInterval(this.InterVal)
          e6 = parseInt(e6)
          switch (e6) {
            case 1:
              this.audio.src = 'https://music.hwkxk.cf/api/?id=' + e4 + '&source=kuwoST'
              break;
            case 2:
              this.audio.src = 'https://music.hwkxk.cf/api/?source=WYHD&id=' + e4
              break
          }
          this.audio.oncanplaythrough = () => {
            this.audio.play()
            clearInterval(this.InterVal)
            this.rotateImg()
            this.songName = e1
            this.title.innerHTML = e1 + '-' + e2
            this.songAuthor = e2
            this.process.max = this.audio.duration
            var minute = Math.floor(this.audio.duration / 60)
            var showMinute = minute >= 10 ? minute.toString() : '0' + minute
            var second = (Math.floor(this.audio.duration) % 60).toFixed()
            var showSecond = second >= 10 ? second.toString() : '0' + second
            this.timeLength = showMinute + ':' + showSecond
          }
          this.audio.addEventListener('timeupdate', () => {
            this.process.value = this.audio.currentTime
            var minute = Math.floor(this.audio.currentTime / 60)
            var showMinute = minute >= 10 ? minute.toString() : '0' + minute
            var second = (Math.floor(this.audio.currentTime) % 60).toFixed()
            var showSecond = second >= 10 ? second.toString() : '0' + second
            this.currentTime = showMinute + ':' + showSecond

          })
          this.event = e3
          this.clientWidth = e5.srcElement.clientWidth
          if (e5.srcElement.className === "playList") {
            for (var i = 0; i < this.loves.length; i++) {
              if (this.loves[i].url == e4) {
                return
              }
            }
            this.loves.push({ name: e1, author: e2, url: e4, flag: e6 })
            this.id = this.loves.length - 1
          }
          else {
            this.id = e3
          }
          if (this.loves.length > 50) {
            this.loves.shift()
          }
        }
        else {
          if (this.audio.paused) {
            this.audio.play()
            this.rotateImg()
          }
          else {
            this.audio.pause()
            clearInterval(this.InterVal)
          }
        }
      },
      // 搜索框聚焦定型
      focus(e) {
        var input = e.srcElement
        input.style.width = '255px'
        input.style.backgroundColor = 'azure'
      },
      // 搜索框失去焦点回到原型
      blur(e) {
        var input = e.srcElement
        input.style.width = '155px'
        input.style.backgroundColor = 'transparent'
      }
    }
  })
</script>

</html>